import EditBase from "./EditBase";
import { toEnvelopedGeojson } from "./utils";

export default class EditControl extends EditBase {
	constructor(map) {
		super(map);

		this.editLayerId = "edit-pan-layer";

		this.startPoint = null;

		this.initEditLayer();
	}

	initEditLayer() {
		const { map, editLayerId } = this;

		const editLPanLayer = {
			id: editLayerId,
			type: "fill",
			source: {
				type: "geojson",
				data: {
					type: "FeatureCollection",
					features: [],
				},
			},
			paint: {
				"fill-color": "yellow",
				"fill-opacity": 0.1,
				"fill-outline-color": "red",
			},
		};

		map.addLayer(editLPanLayer);

		this.editSource = map.getSource(editLayerId);
	}

	onMouseDown(e) {
		e.preventDefault();

		const { canvas, map } = this;

		canvas.style.cursor = "grab";

		this.startPoint = e.lngLat;

		map.on("mousemove", this.moveFunc);
		map.once("mouseup", this.upFunc);
	}

	onUp() {
		const { canvas, map } = this;

		this.startPoint = null;

		canvas.style.cursor = "";
		map.off("mousemove", this.moveFunc);
	}

	onMove(callback, e) {
		const { canvas, startPoint, points, editSource } = this;

		canvas.style.cursor = "grabbing";

		const coords = e.lngLat;

		const distLng = coords.lng - startPoint.lng;
		const distLat = coords.lat - startPoint.lat;

		this.startPoint = coords;

		const newPoints = points.map((point) => [
			point[0] + distLng,
			point[1] + distLat,
		]);

		// 计算平移后的点
		this.points = newPoints;

		const data = toEnvelopedGeojson(newPoints);
		editSource.setData(data);

		callback(newPoints);
	}

	updateEditSource(points) {
		const data = toEnvelopedGeojson(points);
		this.editSource.setData(data);

		this.points = points;
	}
}
